package com.bluedot.www.core.utils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

/**
 * 数据库工具
 *
 * @author GUOZHIPENG
 * @version 1.0
 * @date 2021/8/8 15:55
 */
public class DataBaseUtil {
    private static final String ROOT = "root";
    private static final String IP_ADDRESS = "127.0.0.1";
    private static final String PWD = "root";
    private static final String DBNAME = "db1";
    private static final String BACK_PATH = Objects.requireNonNull(DataBaseUtil.class.getClassLoader().getResource("static/backup.sql")).getPath().replaceFirst("/", "");

    /**
     * 备份数据库（暴露）
     *
     * @author GUOZHIPENG
     * @date 2021/8/8 16:11
     */
    public static InputStream dbBackUp() {
        return dbBackUp(IP_ADDRESS, ROOT, PWD, DBNAME);
    }

    /**
     * @return java.io.InputStream
     * @author Deng HongWei
     * @date 2021/9/4 22:34
     */
    public static boolean dbRecover(InputStream in) {
        return dbRecover(IP_ADDRESS, ROOT, PWD, DBNAME, BACK_PATH, in);
    }


    /**
     * 备份数据库（实际）
     *
     * @param ipAddress IP地址
     * @param root      用户名
     * @param pwd       密码
     * @param dbName    数据库名称
     * @return java.io.InputStream
     * @author Deng HongWei
     * @date 2021/9/4 22:15
     */
    private static InputStream dbBackUp(String ipAddress, String root, String pwd, String dbName) {
        StringBuffer sb = new StringBuffer();
        sb.append("mysqldump");
        sb.append(" -h" + ipAddress);
        sb.append(" -u" + root);
        sb.append(" -p" + pwd);
        sb.append(" " + dbName);
        System.out.println("cmd命令为：" + sb.toString());
        Runtime runtime = Runtime.getRuntime();
        System.out.println("开始备份：" + dbName);
        Process process = null;
        try {
            process = runtime.exec("cmd /c" + sb.toString());
        } catch (IOException e) {
            System.out.println("备份失败!");
            return null;
        }
        InputStream inputStream = process.getInputStream();
        System.out.println("备份成功!");
        return (inputStream != null ? inputStream : new ByteArrayInputStream(new byte[0]));
    }

    /**
     * 数据库恢复（实际）
     *
     * @param ipAddress IP地址
     * @param root      用户名
     * @param pwd       密码
     * @param dbName    数据库名称
     * @param filePath  sql恢复文件路径
     * @param in        云端返回的数据流
     * @return boolean
     * @author Deng HongWei
     * @date 2021/9/4 22:32
     */
    private static boolean dbRecover(String ipAddress, String root, String pwd, String dbName, String filePath, InputStream in) {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), StandardCharsets.UTF_8));
            int len;
            char[] cbuf = new char[1024];
            while ((len = br.read(cbuf)) != -1) {
                bw.write(cbuf, 0, len);
            }
            in.close();
            br.close();
            bw.close();
            StringBuilder sb = new StringBuilder();
            sb.append("mysql");
            sb.append(" -h" + ipAddress);
            sb.append(" -u" + root);
            sb.append(" -p" + pwd);
            sb.append(" " + dbName + " < ");
            sb.append(filePath);
            System.out.println("cmd命令为：" + sb.toString());
            System.out.println("开始还原数据");
            Runtime.getRuntime().exec("cmd /c" + sb.toString());
            System.out.println("还原成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }
}
